package com.ttbj.controller.slideshow;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ttbj.api.dto.Page;
import com.ttbj.api.dto.slideshow.SlideShowDto;
import com.ttbj.api.exception.BusinessException;
import com.ttbj.api.slideshow.SlideshowService;
import com.ttbj.constant.annotation.SystemControllerLog;
import com.ttbj.core.util.DateUtils;
import com.ttbj.util.ViewDataUtil;


//轮播图（幻灯片）controller
@Controller
public class SlideShowController {
	
	@Autowired
	private SlideshowService slideshowService;
	
	/**
	 * 配置页面
	 * @return
	 */
	@RequestMapping(value="/slideshow/slide_show_mag.htm")
	public String slide_show_mag() {
		return "/slideshow/slide_show_mag";
	}
	
	/**
	 * 修改配置页面
	 * @return
	 */
	@RequestMapping(value="/slideshow/edit_show_slide.htm")
	public String edit_show_slide() {
		return "/slideshow/edit_show_slide";
	}
	
	/**
	 * 上传幻灯片页面
	 * @return
	 */
	@RequestMapping(value="/slideshow/slide_show_upload.htm")
	public String slide_show_upload() {
		return "/slideshow/slide_show_upload";
	}
	
	/**
	 * 所有幻灯片展示页面
	 * @return
	 */
	@RequestMapping(value="/slideshow/slide_show_list.htm")
	public String slide_show_list() {
		return "/slideshow/slide_show_list";
	}
	
	/**
	 * 查询所有的幻灯片配置信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/slideshow/getSlideShowMag.htm",method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
    @ResponseBody
	public String getSlideShowMag(HttpServletRequest request, Page page) {
		List<SlideShowDto> showDtos = this.slideshowService.findAllSlideShowInfoPage(page);
		int count = 0;
		if (null != showDtos) {
			count = this.slideshowService.findAllSlideShowInfoPageCount();
		}
		return ViewDataUtil.buildSuccessPageJson("幻灯片信息", showDtos, count);
	}
	
	/**
	 * 用于在主页显示出所有设置的幻灯片
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/slideshow/getSlideShowInfo.htm",method=RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
    @ResponseBody
	public String getSlideShowInfo(HttpServletRequest request) {
		List<SlideShowDto> showDtos = this.slideshowService.findAAllSlideShowOrder();
		return ViewDataUtil.buildSuccessJson("信息", showDtos);
	}
	
	/**
	 * 通过幻灯片id获取信息
	 * @param request
	 * @param slideId id
	 * @return
	 */
	@RequestMapping(value="/slideshow/echoSlideShowById.htm",method=RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
    @ResponseBody
	public String echoSlideShowById(HttpServletRequest request, @RequestParam Integer slideId) {
		SlideShowDto showDto = this.slideshowService.findSlideShowInfoById(slideId);
		return ViewDataUtil.buildSuccessJson("信息", showDto);
	}
	
	/**
	 * 增加幻灯片信息
	 * @param request
	 * @param slideShowDto
	 * @return
	 */
	@RequestMapping(value="/slideshow/addToSlideShowInfo.htm",method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
    @ResponseBody
    @SystemControllerLog(description="增加幻灯片信息")
	public String addToSlideShowInfo(HttpServletRequest request, SlideShowDto slideShowDto) {
		try {
			this.slideshowService.addSlideShowInfo(slideShowDto);
			return ViewDataUtil.buildSuccessJson("增加成功");
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
	}
	
	/**
	 * 修改幻灯片信息
	 * @param request
	 * @param slideShowDto
	 * @return
	 */
	@RequestMapping(value="/slideshow/modifySlideShowInfo.htm",method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
    @ResponseBody
    @SystemControllerLog(description="修改幻灯片信息")
	public String modifySlideShowInfo(HttpServletRequest request, SlideShowDto slideShowDto) {
		try {
			this.slideshowService.editSlideShowInfoById(slideShowDto);
			return ViewDataUtil.buildSuccessJson("修改成功");
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
	}
	
	/**
	 * 删除某一个幻灯片配置
	 * @param request
	 * @param slideId
	 * @return
	 */
	@RequestMapping(value="/slideshow/delSlideShowInfo.htm",method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
    @ResponseBody
    @SystemControllerLog(description="删除幻灯片信息")
	public String delSlideShowInfo(HttpServletRequest request, SlideShowDto slideShowDto) {
		try {
			this.slideshowService.delSlideShowInfoById(slideShowDto);
			return ViewDataUtil.buildSuccessJson("删除成功");
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
	}
	
	/**
	 * 读取img/slideshow 文件夹下所有的图片
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/slideshow/getSlideImgNames.htm",method=RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
    @ResponseBody
	public String getSlideImgNames(HttpServletRequest request) {
		File file = new File(request.getSession().getServletContext().getRealPath("/img/slideshow"));
		System.out.println(file.getPath());
		File[] fileList = file.listFiles();
		List<String> imgNames = new ArrayList<>();
		for (int i = 0; i < fileList.length; i++) {
			String fileName = fileList[i].getName();
			imgNames.add(fileName);
		}
		return ViewDataUtil.buildSuccessJson("图片展示", imgNames);
	}
	
	/**
     * 上传轮播图片
     * @param request
     * @param response
     * @param file 上传的图片，支持多图片
     * @throws Exception
     */
    @RequestMapping(value="/slideshow/insert.htm",method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
    @ResponseBody
    public String insert(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile[] file) {
        if(file != null && file.length > 0) {
            //组合image名称，“;隔开”
            List<String> fileName =new ArrayList<String>();
            try {
                for (int i = 0; i < file.length; i++) {
                    if (!file[i].isEmpty()) {
                        //上传文件，随机名称，";"分号隔开
                        fileName.add(uploadImage(request, "/img/slideshow/", file[i], true));
                    }
                }
                //上传成功
                if(fileName != null && fileName.size() > 0){
                    return ViewDataUtil.buildSuccessJson("上传成功");
                }else {
                	return ViewDataUtil.buildFailureJson(1, "上传失败！文件格式错误");
                }
            } catch (Exception e) {
            	return ViewDataUtil.buildFailureJson(2, "上传出现异常！异常出现在：class.SlideShowController.insert()");
            }
        }else {
            return ViewDataUtil.buildFailureJson(3, "没有检测到文件");
        }
    }
    
    /**
     * 删除img/slideshow 文件夹下的某一个图片
     * @param fileName
     * @return
     */
    @RequestMapping(value="/slideshow/delSlideImg.htm",method=RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
    @ResponseBody
    public String delSlideImg(HttpServletRequest request,@RequestParam String fileName) {
    	if (StringUtils.isBlank(fileName)) {
    		return ViewDataUtil.buildFailureJson(1, "非法操作");
		}
    	//图片文件
    	File file = new File(request.getSession().getServletContext().getRealPath("/img/slideshow/") + fileName);
    	if (file.exists() && file.isFile()) {
			file.delete();
			return ViewDataUtil.buildSuccessJson("删除成功");
		}else {
			return ViewDataUtil.buildFailureJson(1, "图片已不存在，删除失败");
		}
    }
    
    
    /**
     * 上传图片 原名称
     * @param request 请求
     * @param path_deposit 存放位置(路径)
     * @param file 文件
     * @param isRandomName 是否随机名称
     * @return 完整文件路径
     */
    public static String uploadImage(HttpServletRequest request,String path_deposit,MultipartFile file,boolean isRandomName) {
        //上传
        try {
            String[] typeImg={"gif","png","jpg"};
            if(file!=null){
                String origName=file.getOriginalFilename();// 文件原名称
                System.out.println("上传的文件原名称:"+origName);
                // 判断文件类型
                String type=origName.indexOf(".")!=-1?origName.substring(origName.lastIndexOf(".")+1, origName.length()):null;
                if (type != null) {
                    boolean booIsType = false;
                    for (int i = 0; i < typeImg.length; i++) {
                        if (typeImg[i].equals(type.toLowerCase())) {
                            booIsType = true;
                        }
                    }
                    //类型正确
                    if (booIsType) {
                        //存放图片文件的路径
                        String path=request.getSession().getServletContext().getRealPath(path_deposit);
                        //组合名称
                        String fileSrc=""; 
                        //是否随机名称
                        if(isRandomName){
                            origName=DateUtils.getDateShortStr(new Date())+UUID.randomUUID().toString()+origName.substring(origName.lastIndexOf("."));
                        }
                        //判断是否存在目录
                        File targetFile=new File(path,origName);
                        if(!targetFile.exists()){
                            targetFile.mkdirs();//创建目录
                        }
                        //上传
                        file.transferTo(targetFile);
                        //完整路径
                        fileSrc=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+path_deposit+origName;
                        System.out.println("图片上传成功:"+fileSrc);
                        return fileSrc;
                    }
                }
            }
            return null;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}